/*

 */
package com.insigma.business.qrcode.common.util;

import javax.servlet.http.HttpServletRequest;


public class ClientUtil {

    private ClientUtil(){}

    
    public static String getEndIp(final HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

    
    public static String convertIPToHex(final String ipAddress) {
        Integer result = 0;
        String[] ipAddressInArray = ipAddress.split("\\.");
        for (int i = 3; i >= 0; i--) {
            Integer ip = Integer.parseInt(ipAddressInArray[3 - i]);
            
            
            
            
            
            result |= ip << (i * 8);
        }
        return Integer.toHexString(result);
    }

    public String convertStringToIp2(int ip) {
        StringBuilder sb = new StringBuilder(15);
        for (int i = 0; i < 4; i++) {
            
            
            
            
            sb.insert(0, Integer.toString(ip & 0xff));
            if (i < 3) {
                sb.insert(0, '.');
            }
            
            
            
            
            ip = ip >> 8;
        }

        return sb.toString();
    }

}
